package com.wb.utils.encryption

import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.util.*
import kotlin.jvm.Throws

/**
 * sha - 256 加密
 *
 * @author 祁雪
 */
class SHA256Encryption {

    companion object {

        @kotlin.jvm.Throws(Exception::class)
        fun encode(str: String): String {
            val messageDigest = MessageDigest.getInstance("SHA-256")
            messageDigest.update(str.toByteArray(StandardCharsets.UTF_8))
            return byte2Hex(messageDigest.digest())
        }

        fun byte2Hex(byteArray: ByteArray): String {

            val stringBuffer = StringBuffer()
            var temp: String? = null
            for (i in byteArray.indices) {
                temp = Integer.toHexString(byteArray.get(i).toInt() and 0xFF)
                if (temp.length == 1) {
                    //1得到一位的进行补0操作
                    stringBuffer.append("0")
                }
                stringBuffer.append(temp)
            }
            return stringBuffer.toString()
        }

    }

}

fun main() {

    val salt = UUID.randomUUID().toString()
    val time = (System.currentTimeMillis() / 1000).toString()
    val appKey = "09378f7f1b7d9500"
    val appPass = "QYDDPKNYBgjjpJKaYl5FRp7lvrh8oC9l"

    var input = "fuck"

    if (input.length > 20) {
        input = input.substring(0, 10) + input.length + input.substring(input.length - 10)
    }

    val sign: String = SHA256Encryption.encode(appKey + input + salt + time + appPass)

    println("salt: $salt")
    println("time: $time")
    println("appKey: $appKey")
    println("appPass: $appPass")
    println("input: $input")
    println("sign: $sign")
}